package com.servlet.web;

import cn.hutool.crypto.SecureUtil;
import com.servlet.bean.User;
import com.servlet.utils.BaseServlet;
import com.servlet.utils.ResponseVo;
import com.servlet.utils.ServletUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @Title: UploadServelt
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2023/12/28 10:12
 */
@WebServlet("/uploadfile")
@MultipartConfig  // 单独作为上传的配置
public class UploadServelt extends BaseServlet {


    public void upload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 获取上传大的图片
            Part part = req.getPart("image");  // 获取图片的实体
            // 编写自己的输出流
            // 1 设置保存的文件夹 /upload/2023/12/28
            LocalDate now = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            String format = now.format(formatter);
            String rootpath = "/upload/"+format;
            // 2 设置自己的名字  uuid.类型
            String extension = FilenameUtils.getExtension(part.getSubmittedFileName());
            String imageName = UUID.randomUUID().toString().replace("-","");
            String imageNameType = imageName + "."+extension;
            // 文件夹位置 + 图片的名字  就是服务器的实际路径
            String realPath = req.getRealPath(rootpath + "/" + imageNameType);
            // 图片的输入流
            File file = new File(realPath);
            // 自己要制定一个输出流  将图片的输入流 拷贝到输出流当中
            FileOutputStream fos = FileUtils.openOutputStream(file);
            IOUtils.copy(part.getInputStream(),fos);
            ServletUtils.writeResponse(resp, ResponseVo.ok("上传文件成功!",rootpath + "/" + imageNameType));
        }catch (Exception e) {
            ServletUtils.writeResponse(resp, ResponseVo.error(e.getMessage()));
        }
    }
}
